package test.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import com.google.gdata.client.contacts.ContactQuery;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.TextConstruct;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.util.ServiceException;

/**
 * Google数据访问API测试程序
 * @author shawn
 *
 */
public class GoogleDataApi
{
	public static void main(String[] args) throws IOException, ServiceException
	{
		System.setProperty("java.net.preferIPv4Stack", "true");

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("Google帐号：");
		String account = br.readLine();
		System.out.print("Auth Token： ");
		String token = br.readLine();
		if(! account.endsWith("@gmail.com"))
		{
			account += "@gmail.com";
		}

		URL contactFeedUrl = new URL("http://www.google.com/m8/feeds/contacts/" + account + "/full");
		ContactQuery cq = new ContactQuery(contactFeedUrl);
		cq.setStringCustomParameter("email", "1981");

		ContactsService cs = new ContactsService("abettor.org-angleworm-0.0.1");
		cs.setUserToken(token);
		ContactFeed cf = cs.query(cq, ContactFeed.class);
		System.out.println(cf.getTitle().getPlainText());

		System.out.println("-------------------------------------------------------");
		List<ContactEntry> ces = cf.getEntries();
		for(ContactEntry ce : ces)
		{
			String people = null;
			TextConstruct tc = ce.getTitle();
			if(tc == null)
			{
				people = "*未命名*";
			}
			else
			{
				people = tc.getPlainText();
				if(people == null || people.isEmpty())
				{
					people = "*未命名*";
				}
			}
			System.out.println(people);

			List<Email> emails = ce.getEmailAddresses();
			for(Email email : emails)
			{
				String dispName = email.getDisplayName();
				String addr = email.getAddress();
				if(dispName == null)
				{
					dispName = addr;
				}
				System.out.println("\t" + dispName + " <" + addr + ">");
			}
		}
	}
}
